﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Trackr.Core.DataProvider.SQL
{
	public class SelectQuery : IQuery
	{
		private StringBuilder _sql = new StringBuilder(1024);
		private string[] _selectParams = new string[0];
		private string[] _tableParams = new string[0];
		private string[] _groupByParams = new string[0];
		private List<string> _filterParams = new List<string>();

		public SelectQuery(params string[] selectParams)
		{
			//var q = new SelectQuery();
			this._selectParams = selectParams;
			//return q;
		}
		public SelectQuery From(params string[] tableParams)
		{
			_tableParams = tableParams;
			return this;
		}

		public SelectQuery Where(string key, Operator op, string value)
		{
			_filterParams.Add(string.Format("{0} {1} {2}", key, Enums.GetOperator(op), value));
			return this;
		}
		public SelectQuery And(string key, Operator op, string value)
		{
			_filterParams.Add(string.Format("{0} {1} {2}", key, Enums.GetOperator(op), value));
			return this;
		}

		public SelectQuery GroupBy(params string[] groupByParams)
		{
			_groupByParams = groupByParams;
			return this;
		}

		public string ToSql()
		{
			_sql.Clear();
			_sql.Append(string.Format(" SELECT {0}", string.Join(", ", _selectParams)));
			_sql.Append(" FROM " + string.Join(", ", _tableParams));
			if (_filterParams.Count > 0)
			{
				_sql.Append(" WHERE ");
				_sql.Append(string.Join(" AND ", _filterParams.ToArray()));
			}
			if (_groupByParams.Length > 0)
			{
				_sql.Append(" GROUP BY " + string.Join(", ", _groupByParams));
			}
			return _sql.ToString();
		}
		public override string ToString()
		{
			return ToSql();
		}
	}
}
